import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'

interface Word {
  word: string
  meaning: string
}

interface DictationConfig {
  volume: number
  rate: number
  voice: string
  randomMode: boolean
  showMeaning: boolean
  autoPlay: boolean
  interval: number
  repeatWord: boolean
  repeatCount: number
  repeatDelay: number
}

export const useDictationStore = defineStore('dictation', () => {
  // State
  const words = ref<Word[]>([])
  const currentIndex = ref(0)
  const isPlaying = ref(false)
  const currentMode = ref('dictation') // 'dictation' or 'repeat'
  
  const config = ref<DictationConfig>({
    volume: 1.0,
    rate: 1.0,
    voice: 'Microsoft David - English (United States)',
    randomMode: false,
    showMeaning: true,
    autoPlay: true,
    interval: 3,
    repeatWord: true,
    repeatCount: 2,
    repeatDelay: 2
  })
  
  // 监视words的变化并输出到控制台
  watch(words, (newWords, oldWords) => {
    console.log('词汇列表已更新：', {
      oldLength: oldWords.length,
      newLength: newWords.length,
      firstWord: newWords[0]?.word
    })
  })
  
  // Getters
  const currentWord = computed(() => {
    if (words.value.length === 0) return '-'
    return words.value[currentIndex.value]?.word || '-'
  })
  
  const currentMeaning = computed(() => {
    if (words.value.length === 0) return '请先加载词库'
    return words.value[currentIndex.value]?.meaning || '请先加载词库'
  })
  
  const progress = computed(() => {
    return {
      current: currentIndex.value + 1,
      total: words.value.length
    }
  })
  
  const showMeaning = computed(() => {
    return config.value.showMeaning
  })
  
  // Actions
  const setWords = (newWords: Word[]) => {
    console.log('setWords被调用，新词汇数量:', newWords.length)
    words.value = [...newWords]  // 确保是新的数组引用
    currentIndex.value = 0
    console.log('词汇已设置，currentIndex重置为:', currentIndex.value)
  }
  
  const setMode = (mode: string) => {
    currentMode.value = mode
  }
  
  const setPlaying = (playing: boolean) => {
    isPlaying.value = playing
  }
  
  const nextWord = async () => {
    if (words.value.length === 0) return
    
    try {
      const newIndex: number = await invoke('next_word')
      currentIndex.value = newIndex
    } catch (error) {
      // Fallback to local implementation if backend fails
      if (config.value.randomMode) {
        currentIndex.value = Math.floor(Math.random() * words.value.length)
      } else {
        currentIndex.value = (currentIndex.value + 1) % words.value.length
      }
    }
  }
  
  const prevWord = async () => {
    if (words.value.length === 0) return
    
    try {
      const newIndex: number = await invoke('prev_word')
      currentIndex.value = newIndex
    } catch (error) {
      // Fallback to local implementation if backend fails
      if (currentIndex.value === 0) {
        currentIndex.value = words.value.length - 1
      } else {
        currentIndex.value -= 1
      }
    }
  }
  
  const startDictation = () => {
    currentIndex.value = 0
    isPlaying.value = false
  }
  
  const resetDictation = () => {
    currentIndex.value = 0
    isPlaying.value = false
  }
  
  return {
    // State
    words,
    currentIndex,
    isPlaying,
    currentMode,
    config,
    
    // Getters
    currentWord,
    currentMeaning,
    progress,
    showMeaning,
    
    // Actions
    setWords,
    setMode,
    setPlaying,
    nextWord,
    prevWord,
    startDictation,
    resetDictation
  }
})